# Windows服务卸载脚本
# 用于从Windows Server 2019上卸载.NET 9应用程序服务

param(
    [Parameter(Mandatory=$false)]
    [string]$ServiceName = "LzfyHisService"
)

# 检查是否以管理员权限运行
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Error "此脚本需要管理员权限运行"
    exit 1
}

# 检查服务是否存在
$service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
if (-not $service) {
    Write-Warning "服务 '$ServiceName' 不存在"
    exit 0
}

Write-Host "正在卸载服务 '$ServiceName'..." -ForegroundColor Blue

try {
    # 停止服务
    if ($service.Status -eq 'Running') {
        Write-Host "正在停止服务..." -ForegroundColor Yellow
        Stop-Service -Name $ServiceName -Force -ErrorAction Stop
        
        # 等待服务完全停止
        $timeout = 30
        $elapsed = 0
        do {
            Start-Sleep -Seconds 1
            $elapsed++
            $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
        } while ($service.Status -eq 'Running' -and $elapsed -lt $timeout)
        
        if ($service.Status -eq 'Running') {
            Write-Warning "服务在 $timeout 秒内未能停止，强制终止进程"
            # 这里可以添加强制终止进程的逻辑
        } else {
            Write-Host "服务已停止" -ForegroundColor Green
        }
    }
    
    # 删除服务
    Write-Host "正在删除服务..." -ForegroundColor Yellow
    $deleteResult = sc.exe delete $ServiceName
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "服务 '$ServiceName' 已成功卸载" -ForegroundColor Green
    } else {
        Write-Error "删除服务失败，错误代码: $LASTEXITCODE"
        Write-Host "删除结果: $deleteResult" -ForegroundColor Red
        exit 1
    }
    
} catch {
    Write-Error "卸载服务时发生错误: $($_.Exception.Message)"
    exit 1
}

Write-Host "服务卸载完成!" -ForegroundColor Green